package cn.valo.org.service.impl;

import cn.valo.org.domain.Department;
import cn.valo.org.mapper.DepartmentMapper;
import cn.valo.org.service.IDepartmentService;
import cn.valo.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {
    @Autowired
    private DepartmentMapper departmentMapper;
    @Override
    public void save(Department department) {
        System.out.println("-------------------");
        System.out.println(department);
        departmentMapper.insert(department);//返回自增ID
        this.update(department);
    }

    @Override
    public void update(Department department) {
        String dirPath = "";
        if(department.getParentDepartment() == null){
            //1.新增的是顶级部门  /自己id
            dirPath = "/"+department.getId();
        }else{
            //2.新增的是非顶级部门    找上级部门的dirpath + /自己id
            Department parent = departmentMapper.queryById(department.getParentDepartment().getId());
            dirPath = parent.getDirPath() + "/"+department.getId();
        }
        department.setDirPath(dirPath);
        departmentMapper.update(department);
    }
    @Override
    public List<Department> querytree() {
        List<Department> departments = departmentMapper.queryAll();
        Map<Long,Department> collect = departments.stream().collect(Collectors.toMap(Department::getId, depst -> depst));
        List<Department> firstDepts=new ArrayList<>();
        for(Department dept : departments){
            if(dept.getParent_id()!=null){
                Department parent = collect.get(dept.getParent_id());
                System.out.println(parent);
                if(parent!=null){
                    parent.getChildren().add(dept);
                }
            }else{
                firstDepts.add(dept);
            }
        }
        return firstDepts;
    }


}
